var supplementList = {};
var SupplementList = function () {
    this.dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
    this.rowData; //选中行数据
    supplementList.aStationText = "发出站";
    supplementList.arriveStationText = "到站";
    //初始化信息
    this.init = function () {
        var paramMap = layuiFunciton.getURLParamMap();
        if (paramMap) {
            $("#tranType").val(paramMap["tranType"])
        }
        //获取上个月第一天
        var firstdate = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1);
        //初始化搜索条件 日期范围组件
        //初始化时间选择
        layuiFunciton.layTime({
            elem: '#supplementaryDateStart'
            , format: 'yyyy-MM-dd'
            ,value: supplementList.dateFtt("yyyy-MM-dd", firstdate)
        });
        layuiFunciton.layTime({
            elem: '#supplementaryDateEnd'
            , format: 'yyyy-MM-dd'
            ,value: supplementList.getCurrentMonthLast()
        });
        //初始化搜索条件业务员
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/sysUser/findUserList',
            data: {page: 1, limit: 99999},
            maskState: false,         //是否开启遮罩
            success: function (data) {
                var optionHtml = '<option value="">请选择</option>';
                data.forEach(function (obj, index) {
                    optionHtml += '<option value="' + obj.name + '">' + obj.name + '</option>';
                });
                $("#salesman").html(optionHtml);
            }
        });
        //初始化数据字典
        var businessTypes = "YWLX_T";
        if (paramMap) {
            $("#tranType").val(paramMap.tranType);
            if (paramMap["tranType"] == "1") {//铁路运输
                businessTypes = "YWLX_T";
                //发出站
                supplementList.initSelect("aStation", "ZD");
                //到站
                supplementList.initSelect("arriveStation", "ZD");
            } else if (paramMap["tranType"] == "2") {//水路运输
                businessTypes = "YWLX_S";
                $("#goodsWere").text("提单号");
                $("#aStationText").text("发出港");
                $("#arriveStationText").text("到港");
                supplementList.aStationText = "发出港";
                supplementList.arriveStationText = "到港";
                //发出港
                supplementList.initSelect("aStation", "GK");
                //到港
                supplementList.initSelect("arriveStation", "GK");
            } else if (paramMap["tranType"] == "3") {//公路运输
                //发出站
                supplementList.initSelect("aStation", "ZD");
                //到站
                supplementList.initSelect("arriveStation", "ZD");
                businessTypes = "YWLX_G";
            }
        }
        //业务类型
        supplementList.initSelect("businessTypes", businessTypes);
        //品名
        supplementList.initSelect("ofTheGoods", "Of_the_goods");
        //箱型
        supplementList.initSelect("aBox", "XX");
        //发货单位
        supplementList.initSelect("deliveryUnit", "FHDW");
        //收货人
        supplementList.initSelect("receivingUnit", "SHDW");
        //结算人
        supplementList.initSelect("settlementPeople", "JSR");
        //装货地点
        supplementList.initSelect("standby1", "ZHDD");
    };
    //初始化表格
    this.initTalbe = function () {
        layuiFunciton.tableInit({
            toolbar: false,
            tableId: 'supplementListTableId',
            url: layuiFunciton.URL + '/wb/schedule/types/findSupplement',
            id: 'supplementListId',
            totalRow: true,
            searchFromId: 'searchForm',
            tableFilter: 'supplementListFilter',  //表格监听名称,
            cols: [[
                {type: 'numbers', title: '序号', fixed: 'left'},
                {field: 'supplementaryDate', width: 120, title: '增补日期', sort: true},
                {field: 'salesman', width: 100, title: '业务员', sort: true, totalRowText: '合计：'}
                , {field: 'orderDate', width: 120, title: '下单日期', sort: true}
                , {field: 'dateShipment', width: 120, title: '发运日期', sort: true}
                , {
                    field: 'businessTypes', title: '业务类型', sort: true,
                    templet: function (row) {
                        if(supplementList.dictMap[row.businessTypes]){
                            return supplementList.dictMap[row.businessTypes];
                        }else{
                            return "";
                        }
                    }
                }
                , {
                    field: 'ofTheGoods', title: '品名', sort: true,
                    templet: function (row) {
                        if(supplementList.dictMap[row.ofTheGoods]){
                            return supplementList.dictMap[row.ofTheGoods];
                        }else{
                            return "";
                        }
                    }
                }
                , {
                    field: 'aBox', title: '箱型', sort: true,
                    templet: function (row) {
                        if(supplementList.dictMap[row.aBox]){
                            return supplementList.dictMap[row.aBox];
                        }else{
                            return "";
                        }
                    }
                }
                , {field: 'cartonNo', title: '箱号', sort: true}
                , {
                    field: 'deliveryUnit', title: '发货单位', sort: true,
                    templet: function (row) {
                        if (supplementList.dictMap[row.deliveryUnit]) {
                            return supplementList.dictMap[row.deliveryUnit];
                        } else {
                            return "";
                        }
                    }
                }, {
                    field: 'standby1', title: '装货地点', sort: true,
                    templet: function (row) {
                        if (supplementList.dictMap[row.standby1]) {
                            return supplementList.dictMap[row.standby1];
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    field: 'aStation', title: supplementList.aStationText, sort: true,
                    templet: function (row) {
                        if (supplementList.dictMap[row.aStation]) {
                            return supplementList.dictMap[row.aStation];
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    field: 'arriveStation', title: supplementList.arriveStationText, sort: true,
                    templet: function (row) {
                        if (supplementList.dictMap[row.arriveStation]) {
                            return supplementList.dictMap[row.arriveStation];
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    field: 'receivingUnit', title: '收货人', sort: true/*,
                     templet: function (row) {
                     if (supplementList.dictMap[row.receivingUnit]) {
                     return supplementList.dictMap[row.receivingUnit];
                     } else {
                     return "";
                     }
                     }*/
                }
                , {
                    field: 'settlementPeople', title: '结算人', sort: true,
                    templet: function (row) {
                        if (supplementList.dictMap[row.settlementPeople]) {
                            return supplementList.dictMap[row.settlementPeople];
                        } else {
                            return "";
                        }
                    }
                }
                , {field: 'goodsWere', title: '货票号', sort: true}
                , {
                    field: 'amountCount', title: '增补总额', sort: true,
                    totalRowText: '<span style="color: green" class="amountCount">0.00</span>',
                    templet: function (row) {
                        return Number(row.amountCount).toFixed(2);
                    }
                }
                , {
                    field: 'reviewStatus', title: '状态', sort: true,
                    templet: function (row) {
                        if (row.reviewStatus == 0) {
                            return "待审核";
                        } else if (row.reviewStatus == 1) {
                            return '<span style="color: #009feb">通过</span>';
                        } else if (row.reviewStatus == 2) {
                            return '<span style="color: red">不通过</span>';
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    title: '操作',
                    width: 160,
                    align: "center",
                    fixed: 'right',
                    templet: function (row) {
                        if (row.reviewStatus == 0) {
                            return '<a href="javascript:void(0)" style="color:#009feb;" lay-event="details">详情</a><a href="javascript:void(0)" style="color:#009feb;padding-left: 8px;" lay-event="edit">修改</a><a href="javascript:void(0)" style="color:#009feb;padding-left: 8px;" lay-event="del">删除</a>';
                        } else if (row.reviewStatus == 1) {
                            return '<a href="javascript:void(0)" style="color:#009feb" lay-event="details">详情</a>';
                        } else if (row.reviewStatus == 2) {
                            return '<a href="javascript:void(0)" style="color:#009feb" lay-event="details">详情</a>';
                        }
                    }
                }
            ]],
            returnData: function (res) {
                var amountCount = 0.00;
                res.forEach(function (obj, index) {
                    amountCount = (Number(amountCount) + Number(obj.amountCount)).toFixed(2);
                });
                $(".amountCount").html(amountCount);
            },
            tools: {
                edit: function (row) {
                    layuiFunciton.layerOpen({
                        title: "修改",
                        finder: "form",
                        content: "edit.html",
                        data: row,
                        end: function () {
                            layuiFunciton.refresh('searchForm', 'supplementListId');
                        }
                    });
                },
                details: function (row) {
                    layuiFunciton.layerOpen({
                        title: "详情",
                        finder: "form",
                        content: "details.html",
                        data: row,
                        end: function () {
                            layuiFunciton.refresh('searchForm', 'supplementListId');
                        }
                    });
                }
                , del: function (row) {
                    layuiFunciton.alert({
                        types: 'confirm', title: '是否删除？', success: function () {
                            layuiFunciton.ajaxRequest({
                                url: layuiFunciton.URL + '/wb/schedule/types/deleteSupplement',
                                method: 'post',
                                data: {batchNumber: row.batchNumber},
                                success: function (data) {
                                    if (data > 0) {
                                        layuiFunciton.success('操作成功！', function () {
                                            layuiFunciton.refresh('searchForm', 'supplementListId');
                                        })
                                    } else {
                                        layuiFunciton.warn('操作失败!');
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
    };
    //获取当月第一天
    this.getCurrentMonthFirst = function () {
        var date = new Date();
        date.setDate(1);
        return supplementList.dateFtt("yyyy-MM-dd", date);
    };
    this.trim = function (str) {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    };
    //获取当月最后一天
    this.getCurrentMonthLast = function () {
        var date = new Date();
        var currentMonth = date.getMonth();
        var nextMonth = ++currentMonth;
        var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
        var oneDay = 1000 * 60 * 60 * 24;
        return supplementList.dateFtt("yyyy-MM-dd", new Date(nextMonthFirstDay - oneDay));
    };
    //时间格式化
    this.dateFtt = function (fmt, date) {
        var o = {
            "M+": date.getMonth() + 1,     //月份
            "d+": date.getDate(),     //日
            "h+": date.getHours(),     //小时
            "m+": date.getMinutes(),     //分
            "s+": date.getSeconds(),     //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds()    //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    this.event = function () {
        $("#search").click(function () {
            if($("#supplementaryDateStart").val().length == 0 || $("#supplementaryDateEnd").val().length == 0){
                if(!($("#supplementaryDateStart").val().length == 0 && $("#supplementaryDateEnd").val().length == 0)){
                    layuiFunciton.warn('开始时间和结束时间必填！');
                    return;
                }
            }
            layuiFunciton.refresh('searchForm', 'supplementListId');
        });
        $("#reload").click(function () {
            $("#supplementaryDateStart").val("");
            $("#supplementaryDateEnd").val("");
        });
    };
    //初始化input 搜索
    this.initSelect = function (item,typeCode) {
        $("#"+item).attr("readonly","");
        //引入自定义插件
        layui.config({
            base: '/public/plugin/tableSelect/' //设置自定义插件路径:根据实际路径进行设置
        }).use(['tableSelect'], function() {
            var tableSelect = layui.tableSelect;
            tableSelect.render({
                elem: '#'+item,	//定义输入框input对象
                checkedKey: 'valCode', //表格的唯一建值，非常重要，影响到选中状态 必填
                searchKey: 'valName',	//搜索输入框的name值 默认keyword
                searchPlaceholder: '关键词搜索',	//搜索输入框的提示文字 默认关键词搜索
                table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                    url:layuiFunciton.URL + '/sys/dictVal/getByTypeCode?typeCode='+typeCode,
                    page:false,
                    cols: [[
                        {field: 'valName', title: '请选择（双击）',align: "center"}
                    ]]
                },
                done: function (elem, data) {
                    $('#'+item).val(data.data[0].valName);
                    $('#'+item).siblings("input[type='hidden']").val(data.data[0].valCode);
                }
            });
            var dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
            if($('#'+item).val()){
                $("#" + item).after('<input type="hidden" name="'+item+'" value="'+$('#'+item).val()+'" >');
                $('#'+item).val(dictMap[$('#'+item).val()]);
            }else{
                $("#" + item).after('<input type="hidden" name="'+item+'" value="" >');
            }
        });
    }
};
supplementList = new SupplementList();
supplementList.init();
supplementList.initTalbe();
supplementList.event();